/**
 * @(#)QstServlet
 * 版权声明 厦门畅享信息技术有限公司, 版权所有 违者必究
 *
 *<br> Copyright:  Copyright (c) 2014
 *<br> Company:厦门畅享信息技术有限公司
 *<br> @author ulyn
 *<br> 14-8-15 上午12:54
 *<br> @version 1.0
 *————————————————————————————————
 *修改记录
 *    修改者：
 *    修改时间：
 *    修改原因：
 *————————————————————————————————
 */
package cn.ulyn.seckill.servlet;

import cn.ulyn.seckill.mockclient.Browser;
import cn.ulyn.seckill.mockclient.SeckillOrderCreator;
import cn.ulyn.seckill.util.JsonResponse;
import cn.ulyn.seckill.util.ResponseHelper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sunsharing.component.utils.base.StringUtils;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <pre></pre>
 * <br>----------------------------------------------------------------------
 * <br> <b>功能描述:</b>
 * <br>
 * <br> 注意事项:
 * <br>
 * <br>
 * <br>----------------------------------------------------------------------
 * <br>
 */
public class QstServlet extends HttpServlet {
    private static JSONObject qstTemp = new JSONObject();
    private static boolean canCommit = true;
    Logger logger = Logger.getLogger(QstServlet.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        JsonResponse jr = new JsonResponse();
        String cookieStr = req.getParameter("cookieStr");
        String url = req.getParameter("url");
        String answer = req.getParameter("answer");
        boolean isStock2 = "stock2".equals(req.getParameter("type"));
        if (isStock2 && StringUtils.isBlank(answer)) {
            jr.setStatus(false);
            jr.setMsg("提交答案不能为空");
            ResponseHelper.printOut(resp, jr);
            return;
        }
        if (isStock2) {
            //容错answer操作
//            answer = correct(answer);
            answer = URLEncoder.encode(answer, "gb2312");
            url = url + "&an=" + answer;
            while (!canCommit) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        try {
            logger.info("请求url：" + url);
            String result = Browser.getInstance().get(url, cookieStr);
            logger.info("返回：" + result);
            JSONObject o = JSON.parseObject(result);
            if (isStock2) {
                //二次提交订单操作，不考虑是否秒成功，直接提交
                SeckillOrderCreator creator = new SeckillOrderCreator(qstTemp, o, req, answer);
                String orderUrl = creator.generalRequestUrl();
                logger.info("二次提交url：" + orderUrl);
                result = Browser.getInstance().get(orderUrl, cookieStr);
                logger.info("二次提交返回：" + result);
                o = JSON.parseObject(result);
            }
            String qst = o.getString("qst");
            if (!StringUtils.isBlank(qst)) {
                qstTemp = o;
                long now = o.getLong("now");
                ctrlNowCanComit(now);
            } else {
                canCommit = true;
            }
            jr.setData(o);
        } catch (Exception e) {
            jr.setStatus(false);
            jr.setMsg(e.getMessage());
            logger.error("请求异常", e);
        }
        ResponseHelper.printOut(resp, jr);
    }

    private void ctrlNowCanComit(long now) {
        Date date = new Date(now);
        int sec = date.getSeconds();
        if (sec < 3) {
            canCommit = false;
            String nowStr = Long.toString(now);
            final int sleepTime = 2800 - sec * 1000 + Integer.parseInt(nowStr.substring(nowStr.length() - 4));
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(sleepTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    canCommit = true;
                }
            }).start();
        }
    }

    private String correct(String an) {
        if (qstTemp == null || qstTemp.size() == 0) {
            return an;
        }
        int len = qstTemp.getIntValue("len");
        String tip = qstTemp.getString("tip");
        if (!StringUtils.isBlank(tip)) {
            //判断
            try {
                String decodeTip = new String(tip.getBytes(), "utf-8");
                //去掉提示的字中没有的
                List<String> anChars = new ArrayList<String>();
                for (int i = 0, l = an.length(); i < l; i++) {
                    String s = an.substring(i, i + 1);
                    if (decodeTip.indexOf(s) != -1) {
                        anChars.add(s);
                    }
                }
                StringBuilder sb = new StringBuilder();
                for (String s : anChars) {
                    sb.append(s);
                }
                an = sb.toString();

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        if (an.length() > len) {
            an = an.substring(0, len);
        }
        return an;
    }
}

